package com.example.administrator.familfinalcialmanagement.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.administrator.familfinalcialmanagement.GRActivity;
import com.example.administrator.familfinalcialmanagement.MainActivity;
import com.example.administrator.familfinalcialmanagement.R;
import com.example.administrator.familfinalcialmanagement.bean.GreenDaoUtils;
import com.example.administrator.familfinalcialmanagement.bean.TimeBean;
import com.example.administrator.familfinalcialmanagement.bean.UserInfoBean;
import com.example.administrator.familfinalcialmanagement.databinding.FragmentTimeBinding;
import com.example.administrator.familfinalcialmanagement.greendao.gen.TimeBeanDao;
import com.example.administrator.familfinalcialmanagement.util.BHThreadPool;
import com.example.administrator.familfinalcialmanagement.util.LogUtil;
import com.example.administrator.familfinalcialmanagement.util.SensorManagerHelper;
import com.example.administrator.familfinalcialmanagement.util.SpUtils;
import com.example.administrator.familfinalcialmanagement.util.TimeUtil;
import com.example.administrator.familfinalcialmanagement.util.ToastUtil;
import com.example.administrator.familfinalcialmanagement.util.dialog.InCommonDialog;
import com.example.administrator.familfinalcialmanagement.util.dialog.SetTimeDialog;
import com.example.administrator.familfinalcialmanagement.util.listener.OnGRClickListener;

import jp.wasabeef.glide.transformations.BlurTransformation;

/**
 * Created by 86178 on 2019/11/24.
 * author mogen
 * 用心，成就一切。
 */

public class TimeFragment extends BaseLazyFragment {

    FragmentTimeBinding bingding;
    boolean isTrue = false, isFirst = false;
    Runnable runnable;
    String allTime;

    TimeBeanDao timeBeanDao = GreenDaoUtils.getSingleTon().getmDaoSession().getTimeBeanDao();
    TimeBean timeBean;

    UserInfoBean bean = (UserInfoBean) SpUtils.getBean("user_info_bean");

    String timeRes = "00:00:00";

    @Override
    public int setLayoutId() {
        return R.layout.fragment_time;
    }

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        bingding = DataBindingUtil.inflate(LayoutInflater.from(getActivity()), R.layout.fragment_time, container, false);
        bingding.setFragment(this);
        return bingding.getRoot();
    }

    @SuppressLint("MissingPermission")
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Glide.with(this)
                .load(R.drawable.icon_music_bg)
                .apply(RequestOptions.bitmapTransform(new BlurTransformation(25, 10)))
                .into(bingding.ivModuleBG);

        bingding.tvModuleSetTime.setOnClickListener(this);
        bingding.tvModuleStartTime.setOnClickListener(this);
    }


    @Override
    protected void onVisible() {

    }

    @Override
    public void onPause() {
        super.onPause();
        isTrue = false;
        allTime = "00:00:00";
        bingding.tvModuleTime.setText(allTime);
    }

    @Override
    protected void lazyLoad() {
        SensorManagerHelper sensorHelper = new SensorManagerHelper(getActivity());
        //判断手机是否抖动，抖动则暂停倒计时
        sensorHelper.setOnShakeListener(new SensorManagerHelper.OnShakeListener() {
            @Override
            public void onShake() {
                isTrue = false;
                isFirst = false;
                bingding.tvModuleTime.setText("00:00:00");
                allTime = "00:00:00";
            }

            @Override
            public void onStop() {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvModuleSetTime:
                SetTimeDialog dialog = new SetTimeDialog(getActivity());
                dialog.show();
                dialog.setOnGRClickListener(new OnGRClickListener() {
                    @Override
                    public void setOnConfirmClick(String res) {
                        allTime = res;
                        bingding.tvModuleTime.setText(res);
                    }

                    @Override
                    public void setOnCloseClick() {

                    }
                });
                break;
            case R.id.tvModuleStartTime:
                if (TextUtils.isEmpty(allTime) || "00:00:00".equals(allTime)) {
                    InCommonDialog dialogSecond = new InCommonDialog(getActivity());
                    dialogSecond.setTitleText("请先设置时间");
                    dialogSecond.show();
                    return;
                }
                //打开存储数据库开关
                isFirst = true;
                runRun();
                break;
            default:
        }
    }


    public void runRun() {
        runnable = new Runnable() {
            @Override
            public void run() {
                while (isTrue) {
                    SystemClock.sleep(1000);
                    if (!"00:00:00".equals(bingding.tvModuleTime.getText().toString().trim())) {
                        String[] time = bingding.tvModuleTime.getText().toString().trim().split(":");
                        int timeLone = Integer.valueOf(time[0]) * 3600 + (Integer.valueOf(time[1]) * 60)
                                + Integer.valueOf(time[2]);
                        Message msg = Message.obtain();
                        msg.what = 0x01;
                        msg.obj = timeLone + "";
                        mHandler.sendMessage(msg);
                    } else {
                        if (isFirst) {
                            isFirst = false;
                            LogUtil.e("handler发送");
                            Message msg = Message.obtain();
                            msg.what = 0x02;
                            msg.obj = "0";
                            mHandler.sendMessage(msg);
                        }
                    }
                }
            }
        };

        BHThreadPool.getInstance().executeTask(runnable);
        isTrue = true;
    }


    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0x01:
                    String timeRes = (String) msg.obj;
                    LogUtil.e("接收一次信息-->" + timeRes);
                    bingding.tvModuleTime.setText(TimeUtil.getTime((Integer.valueOf(timeRes) - 1) * 1000));
                    break;
                case 0x02:
                    isTrue = false;
                    bingding.tvModuleTime.setText("00:00:00");
                    timeBean = new TimeBean();
                    timeBean.setAllTime(allTime);
                    timeBean.setDayTime(TimeUtil.getNowTime().split(" ")[0]);
                    if (bean != null) {
                        timeBean.setName(bean.getName());
                    }

                    String[] time = allTime.split(":");
                    int timeLone = Integer.valueOf(time[0]) * 3600 + (Integer.valueOf(time[1]) * 60)
                            + Integer.valueOf(time[2]);
                    timeBean.setFive(timeLone);
                    timeBeanDao.insert(timeBean);
                    LogUtil.e("记录添加一次");
                    ToastUtil.showToast("计时结束");
                    break;
            }
            super.handleMessage(msg);
        }
    };


}
